package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.TbUserMapper;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TbUserServiceImpl implements TbUserService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    TbUserMapper tbUserMapper;
    @Override
    public R login(LoginInfoVo loginInfoVo) {
        String mobile = loginInfoVo.getUserMobile();
        String code = stringRedisTemplate.opsForValue().get(mobile);
        if(code == null){
            return R.ERROR(500,"手机号不存在");
        }
        if(!code.equals(loginInfoVo.getUserCode())){
            return R.ERROR(500,"验证码错误");
        }
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getMobile, mobile));
        if (tbUser == null){
            return R.ERROR(500,"手机号不存在");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("nickName", tbUser.getNikeName())
                .compact();
        String tokenKey = "token-"+tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,5,TimeUnit.MINUTES);
        tbUser.setToken(token);


        return R.OK(tbUser);
    }

    @Override
    public R sendCode(String code, String mobile) {
        String key = code;
        if(!stringRedisTemplate.hasKey(key)){
            return R.ERROR(500,"图片验证码失效");
        }
        String UserCode = RandomUtil.randomNumbers(4);
        stringRedisTemplate.opsForValue().set(mobile,UserCode,5, TimeUnit.MINUTES);
        MobileMessageUtil.sendMobileMessage(mobile,UserCode);

        return R.OK();
    }

    @Override
    public R addUser(TbUser tbUser) {

        tbUser.setPrice(30.0);
        tbUserMapper.insert(tbUser);
        return R.OK();
    }

    @Override
    public R updateUser(TbUser tbUser) {
        TbUser tbUser1 = new TbUser();
        Double price = tbUser1.getPrice();
        tbUser.setPrice(price+tbUser.getPrice());
        tbUserMapper.updateById(tbUser);
        return R.OK();
    }
}
